#include <stdio.h>
#include <stdlib.h>
#include "format.h"
#include "utils.h"


int main(int argc,char **argv)
{
	if(argc!=2)
	{
		fprintf(stderr,"Usage: %s file.dat\n",argv[0]);
		exit(1);
	}

	FILE *in=open_file(argv[1],"rb+",NULL,"Couldn't open file \"%s\".\n");

	fseek(in,0,SEEK_END);
	int length=ftell(in);
	fseek(in,0,SEEK_SET);

	u_int8_t bytes[length];
	fread(bytes,1,length,in);

	switch(analyze_file(bytes,length))
	{
		case FILE_INCOMPLETE:
			fprintf(stderr,"Data in file \"%s\" is incomplete.\n",argv[1]);
			exit(2);
		break;
		case FILE_FORMAT_INVALID:
		case FILE_SIZE_INVALID:
			fprintf(stderr,"Data in file \"%s\" is corrupted.\n",argv[1]);
			exit(3);
		break;

		case FILE_CHECKSUM_INVALID:
			fprintf(stderr,"Checksum incorrect, fixing.\n");
		break;

		default:
			fprintf(stderr,"Checksum already correct.\n");
			exit(0);
		break;
	}

	fix_checksum(bytes,length);

	int size=file_size(bytes,length);
	fseek(in,size-4,SEEK_SET);

	fwrite(&bytes[size-4],1,4,in);

	fclose(in);
}
